/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/

(function(K) {
})(KindEditor);

KindEditor.plugin('webuploader_bath', function(K) {
	var self = this, name = 'webuploader_bath',
	webpath = self.webpath,
	imgpath = self.imgpath,
	json = [],
	lang = self.lang(name + '.');
	self.plugin.multiImageDialog = function(options) {
		var html = [
			'<div>',
			'<div id="filePicker2" style="margin:10px;width:108px;" >选择图片</div>',
			'<div class="swfupload" id="swfuploadDiv">',
			 '<div id="fileList2" class="uploader-list2"  maxLimit ="5" objName="accessory" fex_multiple="true"></div>',
			'</div>',
			'</div>'
		].join('');
		
		var dialog = self.createDialog({
			name : name,
			width : 650,
			height : 510,
			title : self.lang(name),
			body : html,
			previewBtn : {
				name : lang.insertAll,
				click : function(e) {
					
					for (var i=0;i<json.length;i++){
						var path = imgpath+json[i].path+json[i].ext;
						self.insertHtml('<img src="'+path+'" /><br />');
					}
					//self.dialogs[0].remove();
					self.hideDialog().focus();

				}
			},
			yesBtn : {
				name : lang.clearAll,
				click : function(e) {
					//swfupload.removeFiles();
					$('#fileList2').empty();
					json = [];
		            for (var i=0;i<json.length;i++){
		            	var jsonObj = json[i];
		            	if(jsonObj.fileId==file.id){
		            		json.splice(i,1);
		            		//fileList.attr("json",json);
		            		break;
		            	}
		            }
		           
				}
			},
			beforeRemove : function() {
				json = [];
				//swfupload.remove();
			}
		}),
		div = dialog.div;
		
		var upLoaderOptions={
				fileList : $('#fileList2'),
				filePickerId : '#filePicker2',
				webPath : webpath,
				imgPath : imgpath,
				json : json,
				imgList : $('#front_img'),
				multiple:'true',
				//图片上传完成处理完后最终返回的图片数组
				successcallback:function(returnJson){
					json = returnJson;
				}
		};
		
		
		fileUpload(upLoaderOptions);
		
		//fileUpload(webpath,imgpath,$('#fileList2'),"#filePicker2",json);

		return dialog;
	};
	self.clickToolbar(name, function() {
		self.plugin.multiImageDialog({
			clickFn : function (urlList) {
				if (urlList.length === 0) {
					return;
				}
				var html = '';
				K.each(urlList, function(i, url) {
					html += '<img src="' + K.escape(url) + '" data-ke-src="' + K.escape(url) + '" alt="" /><br />';
				});
				self.insertHtml(html);
				// Bugfix: [Firefox] 上传图片后，总是出现正在加载的样式，需要延迟执行hideDialog
				setTimeout(function() {
					self.hideDialog().focus();
				}, 0);
			}
		});
	});
});



function uploadStr2Bool(value,defaultValue){
	if(null==value || (!value) || (value!="true" && value!="false")){
		if(defaultValue=="false"){
			return false;
		}else{
			return true;
		}
	}
	
	if(value=="false"){
		return false;
	}else if(value=="true"){
		return true;
	}
}

//fex webupload 图片上传公共js 方法,3个入参(frontUrl:url前缀  fileList：存放List的div filePickerId:按钮样式  json:json数据，主要是在页面使用，这里采用地址传递
/*function fileUpload(webpath,imgpath,fileList,filePickerId,json){
	
	//初始化div数据
    var $ = jQuery,
        $list = fileList,
        //最多只能上传照片数（默认选择300张)
       // $maxLimit = !(fileList.attr("maxLimit"))?300:fileList.attr("maxLimit"),
        $maxLimit = !(fileList.maxLimit)?300:fileList.maxLimit,
        //是否是单张照片模式(新的代替旧的)
       // $multiple = uploadStr2Bool(fileList.attr("fex_multiple"),"true"),
         $multiple = uploadStr2Bool(fileList.fex_multiple,"true"),
        //总上传张数
        $upLoaderNum = 0,
        //上传成功数		
        $sucessNum=0,
        //上传失败数
        $errorNum = 0,
        //对象名称，如果为空默认为objJson。
       // $objName = !(fileList.attr("objName"))?"objJson":fileList.attr("objName"),
        $objName = !(fileList.objName)?"objJson":fileList.objName,
        //上传成功后是否需要显示名称（后期看情况重新设默认值)
       // $showName = uploadStr2Bool(fileList.attr("showName"),"true"),
        $showName = uploadStr2Bool(fileList.showName,"true"),
        //上传成功后是否需要显示路径（后期看情况重新设默认值)
        //$showPath = uploadStr2Bool(fileList.attr("showPath"),"true"),
        $showPath = uploadStr2Bool(fileList.showPath,"true"),
    	//上传成功后是否需要显示删除按钮
    	//$showDelBtn = uploadStr2Bool(fileList.attr("showDelBtn"),"true"),
    	$showDelBtn = uploadStr2Bool(fileList.showDelBtn,"true"),
        
        // 优化retina, 在retina下这个值是2
        ratio = window.devicePixelRatio || 1,
        // 缩略图大小
        thumbnailWidth = 100 * ratio,
        thumbnailHeight = 100 * ratio,
        
        // Web Uploader实例
        uploader;
    

    // 初始化Web Uploader
    uploader = WebUploader.create({

        // 自动上传。
        auto: true,

        // swf文件路径
        swf:  webpath+'/resources/js/webuploader/Uploader.swf',

        // 文件接收服务端。
        server: webpath+'/seller/fex_upload.htm',

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: {
        	id : filePickerId,
        	//判断是否可以多选
        	multiple :  $multiple
        },
        //最大上传数
        fileNumLimit:$maxLimit,
        // 只允许选择文件，可选。
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        }
    });


    // 当有文件添加进来的时候
    uploader.on('fileQueued', function( file ) {
    	
    	
    	
    	var imgDiv = "";
    	imgDiv ="<div id='img'"+file.id +" width='100' height='100'></div>";
    	
    	//是否显示删除按钮
    	var showDelBtnDiv = "";
		if($showDelBtn==true){
			showDelBtnDiv = "<div id='del'"+file.id+" class='del' style='cursor:pointer; color:#ff4545;'>删除</div>";
		}
    	
		//是否显示名称
    	var showNameDiv = "";
    	if($showName==true){
    		showNameDiv = "<div class='info'>" + file.name + '</div>' ;
    	}
    	
    	var showPathDiv = "";
    	if($showPath==true){
    		showPathDiv = "<div id='path_"+file.id+"'></div>";
    	}
    	
        var $li = $(
                '<div id="' + file.id + '" class="file-item thumbnail" style="float:left;margin-left:10px">' +
                    '<img id="img_'+file.id+'">' +
                    showNameDiv +
                    showDelBtnDiv +
                    showPathDiv+
                '</div>'
                ),
                
            $img = $li.find('img');
        
        $li.on('click', '.del', function() {
        	uploader.removeFile( file,true );
            
            for (var i=0;i<json.length;i++){
            	var jsonObj = json[i];
            	if(jsonObj.fileId==file.id){
            		json.splice(i,1);
            		//fileList.attr("json",json);
            		break;
            	}
            }
            $(this).parent().remove();
        });
        
        //如果是单张模式，则清空div数据
        if($multiple==false){
        	$list.empty()
        	uploader.removeFile( file,true );
            for (var i=0;i<json.length;i++){
            	var jsonObj = json[i];
            	if(jsonObj.fileId==file.id){
            		json.splice(i,1);
            	//	fileList.attr("json",json);
            		break;
            	}
            }
        };  
            
        
        $list.append( $li );

        // 创建缩略图
        uploader.makeThumb( file, function( error, src ) {
            if ( error ) {
                $img.replaceWith('<span>不能预览</span>');
                return;
            }

           // $img.attr( 'src', src );
        }, thumbnailWidth, thumbnailHeight );
        
        $upLoaderNum++;
       // fileList.attr("upLoaderNum",$upLoaderNum);
        
        
        
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress span');

        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<p class="progress"><span></span></p>')
                    .appendTo( $li )
                    .find('span');
        }

        $percent.css( 'width', percentage * 100 + '%' );
    });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on( 'uploadSuccess', function( file,data ) {
    	var $li=$list.find('.file-item');
    	var path = imgpath+data.accessory.path+data.accessory.ext;
    	var imgName = data.accessory.path+data.accessory.ext;
    	var $img = $li.find('#img_'+file.id);
    	$img.attr('src',path);
    	$img.attr('width',100);
    	$img.attr('height',100);
    	var id=$list.attr("type");
    	//var jsonObj = eval("data." + $objName);
    	jsonObj = data.accessory;
//    	jsonObj.num = $sucessNum; 
//    	jsonObj.fileId = file.id;
//        $( '#'+file.id ).addClass('upload-state-done');
//        $("#path_"+file.id).html("<font color='red'>"+response._raw+"</font>");
        json.push(jsonObj);
//        //json.push(response.[$objName]);
//        //fileList.attr("json",json);
//        $sucessNum++;
      
    });

    // 文件上传失败，现实上传出错。
    uploader.on( 'uploadError', function( file ) {
        var $li = $( '#'+file.id ),
            $error = $li.find('div.error');

        // 避免重复创建
        if ( !$error.length ) {
            $error = $('<div class="error"></div>').appendTo( $li );
        }

        $error.text('上传失败');
    });

    // 完成上传完了，成功或者失败，先删除进度条。
    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').remove();
    });
    
    //当文件上传结束后触发。
    uploader.on('uploadFinished',function(file){
    	//fileList.attr("json",json);
    });
}
*/